package com.hxrfid.web.controller.project;

import com.hxrfid.common.annotation.Log;
import com.hxrfid.common.annotation.RepeatSubmit;
import com.hxrfid.common.core.controller.BaseController;
import com.hxrfid.common.core.domain.PageQuery;
import com.hxrfid.common.core.domain.R;
import com.hxrfid.common.core.page.TableDataInfo;
import com.hxrfid.common.core.validate.AddGroup;
import com.hxrfid.common.core.validate.EditGroup;
import com.hxrfid.common.enums.BusinessType;
import com.hxrfid.common.utils.ImageUtils;
import com.hxrfid.common.utils.ZipUtil;
import com.hxrfid.project.domain.bo.BsCardListBo;
import com.hxrfid.project.domain.vo.BsCardListVo;
import com.hxrfid.project.service.IBsCardListService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实体卡列
 *
 * @author hxrfid
 * @date 2025-07-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/project/cardList")
public class BsCardListController extends BaseController {

    private final IBsCardListService iBsCardListService;

    /**
     * 查询实体卡列列表
     */
//    @SaCheckPermission("project:cardList:list")
    @GetMapping("/list")
    public TableDataInfo<BsCardListVo> list(BsCardListBo bo, PageQuery pageQuery) {
        return iBsCardListService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出实体卡列列表
     */
    @Log(title = "实体卡列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BsCardListBo bo, HttpServletResponse response) throws IOException {
        List<BsCardListVo> list = iBsCardListService.queryList(bo);
        List<ZipUtil.QrCodeWithCardNo> qrCodeList = list.stream()
            .map(card -> {
                String string = card.getId().toString();
                try {
                    byte[] imageBytes = ImageUtils.generateQrCodeWithTopText(
                        string, string, 200);
                    return new ZipUtil.QrCodeWithCardNo(string, imageBytes);
                } catch (IOException e) {
                    throw new RuntimeException("生成二维码失败：" + string, e);
                }
            })
            .collect(Collectors.toList());

        byte[] zipBytes = null;
        try {
            zipBytes = ZipUtil.createQrCodeZip(qrCodeList, "qrcode");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=qr_codes.zip");
        response.setContentLength(zipBytes.length);

        try (OutputStream os = response.getOutputStream()) {
            os.write(zipBytes);
            os.flush();
        }
    }

    /**
     * 获取实体卡列详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("project:cardList:query")
    @GetMapping("/{id}")
    public R<BsCardListVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iBsCardListService.queryById(id));
    }

    /**
     * 新增实体卡列
     */
//    @SaCheckPermission("project:cardList:add")
    @Log(title = "实体卡列", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BsCardListBo bo) {
        return toAjax(iBsCardListService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改实体卡列
     */
//    @SaCheckPermission("project:cardList:edit")
    @Log(title = "实体卡列", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BsCardListBo bo) {
        return toAjax(iBsCardListService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除实体卡列
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("project:cardList:remove")
    @Log(title = "实体卡列", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iBsCardListService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    /**
     * 激活卡片
     */
    @PostMapping("/activeCard")
    public R<Void> activeCard(@RequestBody BsCardListBo bo) {
        return toAjax(iBsCardListService.activeCard(bo));
    }
}
